package com.sw.test01.ui.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.sw.test01.ContentHandler;
import com.sw.test01.R;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * xml的解析 pull和sax
 */
public class XmlActivity extends AppCompatActivity {
    private Toolbar tbToolBar;
    private Button btnPull;
    private Button btnSax;
    private TextView tvResult;
    private static final String TAG = "XmlActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xml);
        tbToolBar = (Toolbar) findViewById(R.id.tb_toolbar);
        btnPull = (Button) findViewById(R.id.btn_pull);
        btnSax = (Button) findViewById(R.id.btn_sax);
        tvResult = (TextView) findViewById(R.id.tv_result);

        tbToolBar.setTitle("xml解析");

        btnPull.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            OkHttpClient client = new OkHttpClient();
                            Request request = new Request.Builder()
                                    //指定访问的服务器地址
                                    .url("http://192.168.0.168:8080/parseXml/get_data.xml")
                                    .build();
                            Response response = client.newCall(request).execute();
                            String responseData = response.body().string();
                            parseXMLWithPull(responseData);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });

        btnSax.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            OkHttpClient client = new OkHttpClient();
                            Request request = new Request.Builder()
                                    .url("http://192.168.0.168")
                                    .build();
                            Response response = client.newCall(request).execute();
                            String responseData = response.body().string();
                            parseXMLWithSAX(responseData);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }

    private void parseXMLWithPull(String xmlData) {
        final StringBuilder sb = new StringBuilder();
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(new StringReader(xmlData));
            int eventType = xmlPullParser.getEventType();
            String id = "";
            String name = "";
            String version = "";
            while (eventType != xmlPullParser.END_DOCUMENT) {
                String nodeName = xmlPullParser.getName();
                switch (eventType) {
                    //开始解析某个节点
                    case XmlPullParser.START_TAG:
                        if ("id".equals(nodeName)) {
                            id = xmlPullParser.nextText();
                        } else if ("name".equals(nodeName)) {
                            name = xmlPullParser.nextText();
                        } else if ("version".equals(nodeName)) {
                            version = xmlPullParser.nextText();
                        }
                        break;
                    //完成解析某个节点
                    case XmlPullParser.END_TAG:
                        if ("app".equals(nodeName)) {
                            Log.d(TAG, "id is = " + id);
                            Log.d(TAG, "name is = " + name);
                            Log.d(TAG, "version is = " + version);
                            sb.append(id + ":" + name + ":" + version + "\n");
                        }
                        break;
                }
                eventType = xmlPullParser.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (sb.length() != 0) {
                        String str = sb.toString();
                        tvResult.setText(str);
                    }
                }
            });
        }
    }

    private void parseXMLWithSAX(String xmlData) {
        StringBuilder sb = null;
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            XMLReader xmlReader = factory.newSAXParser().getXMLReader();
            ContentHandler handler = new ContentHandler();
            sb = handler.getSb();
            //将content的实例设置进xmlreader中
            xmlReader.setContentHandler(handler);
            //开始执行解析
            xmlReader.parse(new InputSource(new StringReader(xmlData)));
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            final StringBuilder finalSb = sb;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (finalSb.length() != 0) {
                        String str = finalSb.toString();
                        tvResult.setText(str);
                    }
                }
            });
        }

    }
}
